#读写数据库
import requests, json
from tools.utils import code2openid
import logging
logger = logging.getLogger('info')

# 查询社区
url1 = 'http://127.0.0.1:8001/getCommu'
url2 = 'http://47.111.101.201:8001/getDeviceInfo'
url3 = 'http://47.111.101.201:8001/getSubInfo'
url4 = 'http://47.111.101.201:8001/setSubInfo'
url5 = 'http://47.111.101.201:8001/getHistory'


# 用户注册，注册绑定用户与设备，设备与社区之间的关系
def usrRegister(data):

    # 社区编号，设备id，用户code，验证码
    area = data.get('area')
    deviceid = data.get('deviceid')
    code = data.get('code')
    passwd = data.get('passwd')

    #查询社区编号
    commudata = json.loads(requests.post(url1, data=json.dumps({'code':area})).text).get('result')
    if not commudata:
        return {'errcode': -1, 'errmsg': '请确认社区编号'}
    else:
        if passwd != commudata[0].get('secret'):
            return {'errcode': -1, 'errmsg': '请确认验证码'}


    # 查询设备编号
    devicedata = json.loads(requests.post(url2, data=json.dumps({'deviceid':deviceid})).text).get('result')
    if not devicedata:
        return {'errcode': -1, 'errmsg': '请确认设备编号'}

    # 查询用户是否注册
    userid = code2openid(code)
    #userid = code
    user = json.loads(requests.post(url3, data=json.dumps({'userid':userid})).text)
    device = json.loads(requests.post(url3, data=json.dumps({'deviceid':deviceid})).text)
    # 已注册
    print(user, device, '2'*30)
    if user.get('result') and device.get('result'):
        return {'errcode': -1, 'errmsg': '已注册'}
    elif user.get('result'):
        return {'errcode': -1, 'errmsg': '用户已绑定其他设备'}
    elif device.get('result'):
        return {'errcode': -1, 'errmsg': '设备已被其他用户绑定'}
    else:
        # 可注册, 初始注册设置为未预约
        # 绑定用户与设备的关系
        result = requests.post(url4, data=json.dumps({'deviceid':deviceid, 'userid': userid, 'subed':False}))
        # 绑定设备与小区的对应关系
        result2 = requests.post(url4, data=json.dumps({'deviceid':deviceid, 'userid': userid, 'subed':False}))

        print(result.text)
        return json.loads(result.text)

# 根据用户id获取用户名下的设备，以及设备对应的小区信息
def getDeviceAndCommu(data):
    # 返回值
    deviceinfo = dict()
    errmsg = ''

    userid = code2openid(data.get('code'))
    # 根据用户id获取设备id
    info = json.loads(requests.post(url3, data=json.dumps({'userid':userid})).text)

    print('info ', info)

    if info.get('result'):
        deviceid = info.get('result')[0].get('deviceid')
        deviceinfo['deviceid'] = deviceid
    else:
        errmsg += ' 获取设备id失败 '
    
    # 根据设备id获取小区编码
    area = json.loads(requests.post(url2, data=json.dumps({'deviceid':deviceid})).text)

    print('area ', area)

    if area.get('result'):
        areaid = area.get('result')[0].get('keepword')
        deviceinfo['area'] = areaid
        deviceinfo['maxvolume'] = area.get('result')[0].get('maxVol')
    else:
        errmsg += ' 获取小区编码失败 '


    # 根据小区编码获取小区信息
    commuInfo = json.loads(requests.post(url1, data=json.dumps({'code':areaid})).text)

    print('commuInfo ', commuInfo)

    if commuInfo.get('result'):
         deviceinfo['name'] = commuInfo.get('result')[0].get('name')
         deviceinfo['address'] = commuInfo.get('result')[0].get('address')
         deviceinfo['lng'] = commuInfo.get('result')[0].get('longitude')
         deviceinfo['lat'] = commuInfo.get('result')[0].get('latitude')
    else:
        errmsg += ' 获取小区信息失败 '
    
    if deviceinfo:
        return {'errcode':0, 'errmsg':'', 'deviceInfo':deviceinfo}
    else:
        return {'errcode':-1, 'errmsg':'未获取到设备信息', 'deviceInfo':deviceinfo}



# 根据用户id获取用户名下设备的预约关系
def getUserDevice(data):
    userid = code2openid(data.get('userId'))
    print(userid)
    # 根据用户id获取设备id
    info = json.loads(requests.post(url3, data=json.dumps({'userid':userid})).text)
    print('info ', info)

    return info

# 设置设备预约状态
def SetSub(data):
    userid = code2openid(data.get('userId'))
    deviceid = data.get('deviceId')
    # 根据用户id获取设备id
    result = requests.post(url4, data=json.dumps({'deviceid':deviceid, 'userid': userid, 'subed':True}))

    return json.loads(result.text)

# 获取操作历史
def getHistory(data):
    userid = code2openid(data.get('userId'))
    logger.info('获取用户:{}的历史信息 '.format(userid))
    # 根据用户id获取设备id,根据userid同时获取设备id与
    #info = json.loads(requests.post(url3, data=json.dumps({'userid':userid})).text)
    result = requests.post(url5, data=json.dumps({'userid': userid}))
    return json.loads(result.text)



if __name__ == '__main__':
    data = {'area': 'abc', 'deviceid':'0000000000', 'code':'0000000000', 'passwd':'a23456'}

    print(usrRegister(data))


    
    


    
    
    
